const { Controller } = require("egg");

class AccountController extends Controller {
    // 批量新增限时优惠
    async addAccount() {
        const { ctx } = this;
        const { method, account, goods, isHalfPrice, activityDate, privilegePrice } = ctx.request.body;
        const payLoad = { method, account, isHalfPrice, activityDate, privilegePrice };

        const goodsList = goods.map(goodsId => ({ ...payLoad, goodsId }));
        console.log(ctx.model.Account);
        await ctx.model.Account.insertMany(goodsList)
        ctx.send({ msg: "成功" })
    }
    // 获取优惠列表
    async getAccountList() {
        const { ctx } = this;
        const data = await ctx.model.Account.aggregate([
            {
                $lookup: {
                    localField: "goodsId",
                    foreignField: "_id",
                    from: "Goods",
                    as: "goodsInfo"
                },
            },
            { $unwind: "$goodsInfo" },
            {
                $project: {
                    "goodsInfo.stock": 1,
                    "goodsInfo.image": 1,
                    "goodsInfo.name": 1,
                    "goodsInfo.price": 1,
                    activityDate: 1,
                    goodsId: 1,
                    account: 1,
                    isHalfPrice: 1,
                    method: 1,
                    status: 1,
                    // 这些运算符、条件判断、关系运算都是用数组表示，$cond：条件判断，$multiply：乘，$divide：除
                    // 四则运算：加法（$add）、减法（$subtract）、乘法（$multiply）、除法（$divide）、求模（$mod）
                    // payPrice: { $cond: [{ $eq: ["$method", 1] }, { $multiply: ["$goodsInfo.price", { $divide: ["$account", 10] }] }, "$payPrice"] },

                }
            }])
        data.forEach(item => {
            if (item.method == 1) {
                item.payPrice = item.goodsInfo.price * item.account / 10;
            }
            item.minusPrice = item.goodsInfo.price - item.payPrice;
        })
        ctx.send({ msg: "成功", data })
    }
    // 编辑
    async editAccount() {
        const { ctx } = this;
        const { _id, method, account, isHalfPrice, activityDate } = ctx.request.body;
        await ctx.model.Account.updateOne({ _id }, { method, account, isHalfPrice, activityDate })
        ctx.send({ msg: "成功" })
    }
    // 删除
    async delAccount() {
        const { ctx } = this;
        const { _id } = ctx.params;
        await ctx.model.Account.deleteOne({ _id })
        ctx.send({ msg: "成功" })
    }
}

module.exports = AccountController;